package com.example.administrator.orchardeveryday.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.administrator.orchardeveryday.bean.dbbean.Goods;
import com.example.administrator.orchardeveryday.bean.dbbean.User;

import java.util.ArrayList;

/**
 * Created by Administrator on 15-10-25.
 */
public class DaoImpl implements IDao {
    private UserSqliteOpenHelper helper;

    public DaoImpl() {
        this.helper=new UserSqliteOpenHelper();
    }
    @Override
    public void save(User user) {
        SQLiteDatabase database=helper.getReadableDatabase();
        ContentValues values=new ContentValues();
        values.put("name",user.getName());
        values.put("pwd",user.getPwd());
        database.insert(DbBean.UserDb.TABLE_USER, null, values);
        database.close();
    }

    @Override
    public void save(Goods goods) {
        SQLiteDatabase database=helper.getReadableDatabase();
        ContentValues values=new ContentValues();
        values.put("name",goods.getGoodsName());
        values.put("price",goods.getPrice());
        values.put("number",goods.getNumber());
        database.insert(DbBean.GoodsDb.TABLE_GOODS, null, values);
        database.close();
    }

    @Override
    public User findUser(long id) {
        User user=null;
        SQLiteDatabase database=helper.getReadableDatabase();
        Cursor cursor = database.query(DbBean.UserDb.TABLE_USER, null, null, null, null, null, null);
        while (cursor.moveToNext())
        {
            user = new User(cursor);
        }

        return user;
    }

    @Override
    public ArrayList<Goods> findGoods(long id) {
        ArrayList<Goods> list = new ArrayList<Goods>();
        SQLiteDatabase database=helper.getReadableDatabase();
        Cursor cursor = database.query(DbBean.GoodsDb.TABLE_GOODS, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            Goods goods = new Goods(cursor);
            list.add(goods);
        }
        return list;
    }

    @Override
    public void deleteAll() {
        SQLiteDatabase database=helper.getReadableDatabase();
        database.execSQL(DbBean.GoodsDb.DELETE_CAR);
    }

    @Override
    public void update(Goods goods) {
        SQLiteDatabase database=helper.getReadableDatabase();
        database.execSQL(DbBean.GoodsDb.UPDATE_GOODS,new Object[]{goods.getNumber(),goods.getId()});
    }
}
